<?php

namespace App\Http\Controllers;

use App\Models\Period;
use App\Presenters\StaffPeriodFeePresenter;
use Illuminate\Http\Request;

use App\Http\Requests;
use Illuminate\Support\Facades\Route;
use Prettus\Validator\Contracts\ValidatorInterface;
use Prettus\Validator\Exceptions\ValidatorException;
use App\Http\Requests\StaffPeriodFeeCreateRequest;
use App\Http\Requests\StaffPeriodFeeUpdateRequest;
use App\Repositories\StaffPeriodFeeRepository;
use App\Validators\StaffPeriodFeeValidator;

/**
 * Class StaffPeriodFeesController.
 *
 * @package namespace App\Http\Controllers;
 */
class StaffPeriodFeesController extends Controller
{
    /**
     * @var StaffPeriodFeeRepository
     */
    protected $repository;

    /**
     * @var StaffPeriodFeeValidator
     */
    protected $validator;

    /**
     * StaffPeriodFeesController constructor.
     *
     * @param StaffPeriodFeeRepository $repository
     * @param StaffPeriodFeeValidator $validator
     */
    public function __construct(StaffPeriodFeeRepository $repository, StaffPeriodFeeValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $this->repository->pushCriteria(app('Prettus\Repository\Criteria\RequestCriteria'));

        if (Route::currentRouteName() == 'api.staff-period-fees.index') {
            $staffPeriodFees = $this->repository->with(['staff:id,name,id_card', 'period:id,year,month', 'staffPeriodFeeDetails.dorm:id,code'])
                ->orderBy('period_id', 'desc')
                ->get()
                ->take(3);
            return response()->json($staffPeriodFees);
        } else {
            $this->repository->setPresenter(StaffPeriodFeePresenter::class);
            if (\request()->has('export') && \request()->has('period_id')) {
                //导出
                set_time_limit(0);
                $staffPeriodFees = $this->repository->with(['staff', 'period:id,name,start_date,end_date,status', 'staffPeriodFeeDetails', 'staffPeriodFeeDetails.dorm:id,code'])->findWhere(['period_id' => \request()->get('period_id')]);
            } else {
                //页面显示
                $staffPeriodFees = $this->repository->with(['company', 'staff', 'period:id,name,start_date,end_date,status', 'staffPeriodFeeDetails', 'staffPeriodFeeDetails.dorm:id,code'])
                    ->paginate(\request()->get('limit', 20));
            }

            if (request()->wantsJson()) {
                return response()->json([
                    'data' => $staffPeriodFees,
                ]);
            } else {
                \request()->flash();
            }
            $periods = Period::query()
                //            ->where('status','>',0)
                ->orderBy('id', 'desc')
                ->pluck('name', 'id');
            return view('staffPeriodFees.index', compact('staffPeriodFees', 'periods'));
        }
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  StaffPeriodFeeCreateRequest $request
     *
     * @return \Illuminate\Http\Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function store(StaffPeriodFeeCreateRequest $request)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);

            $staffPeriodFee = $this->repository->create($request->all());

            $response = [
                'message' => 'StaffPeriodFee created.',
                'data'    => $staffPeriodFee->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {
            if ($request->wantsJson()) {
                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $staffPeriodFee = $this->repository->find($id);

        if (request()->wantsJson()) {

            return response()->json([
                'data' => $staffPeriodFee,
            ]);
        }

        return view('staffPeriodFees.show', compact('staffPeriodFee'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $staffPeriodFee = $this->repository->find($id);

        return view('staffPeriodFees.edit', compact('staffPeriodFee'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  StaffPeriodFeeUpdateRequest $request
     * @param  string            $id
     *
     * @return Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function update(StaffPeriodFeeUpdateRequest $request, $id)
    {
        try {

            $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);

            $staffPeriodFee = $this->repository->update($request->all(), $id);

            $response = [
                'message' => 'StaffPeriodFee updated.',
                'data'    => $staffPeriodFee->toArray(),
            ];

            if ($request->wantsJson()) {

                return response()->json($response);
            }

            return redirect()->back()->with('message', $response['message']);
        } catch (ValidatorException $e) {

            if ($request->wantsJson()) {

                return response()->json([
                    'error'   => true,
                    'message' => $e->getMessageBag()
                ]);
            }

            return redirect()->back()->withErrors($e->getMessageBag())->withInput();
        }
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $deleted = $this->repository->delete($id);

        if (request()->wantsJson()) {

            return response()->json([
                'message' => 'StaffPeriodFee deleted.',
                'deleted' => $deleted,
            ]);
        }

        return redirect()->back()->with('message', 'StaffPeriodFee deleted.');
    }
}
